package com.ruiyian.common.utils.jfinsUtil;

import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.Map;

@Slf4j
public class AnalysisInfomationBoard {

    /**
     * 根据返回的命令解析中文
     * @param msg
     */
   public static String getStringValue(Object msg,String flag){
       String str = null;
       try {
           String readMessage = (String) msg;
           // 取（14,16）的数字并进行转进制，取得该字符串有多少字节数
           str = readMessage.substring(14,16);
           int y= Integer.valueOf(str,16);
           // 定义messageCode 为 22，是16到60总共有22个字节,而returnValue则是有多少个地址
           int menssageCode = 22;
           int returnValue = (y-menssageCode)/2;
           String substring = readMessage.substring(64, readMessage.length()-1);
           String str2Str = hexStr2Str(substring,flag);
           String reg = "[^\\u4e00-\\u9fa5]";
           str = str2Str.replaceAll(reg, "");
       } catch (Exception e) {
           log.error(e.getMessage());
       }
       return str;
    }

    /**
     * 16进制转中文
     * @param hex
     * @return
     */
    public static String hexStr2Str(String hex,String code) {
        String hexStr = "";
        String str = "0123456789ABCDEF"; //16进制能用到的所有字符 0-15
        for(int i=0;i<hex.length();i++){
            String s = hex.substring(i, i+1);
            if(s.equals("a")||s.equals("b")||s.equals("c")||s.equals("d")||s.equals("e")||s.equals("f")){
                s=s.toUpperCase().substring(0, 1);
            }
            hexStr+=s;
        }

        char[] hexs = hexStr.toCharArray();//toCharArray() 方法将字符串转换为字符数组。
        int length = (hexStr.length() / 2);//1个byte数值 -> 两个16进制字符
        byte[] bytes = new byte[length];
        int n;
        for (int i = 0; i < bytes.length; i++) {
            int position = i * 2;//两个16进制字符 -> 1个byte数值
            n = str.indexOf(hexs[position]) * 16;
            n += str.indexOf(hexs[position + 1]);
            // 保持二进制补码的一致性 因为byte类型字符是8bit的  而int为32bit 会自动补齐高位1  所以与上0xFF之后可以保持高位一致性
            //当byte要转化为int的时候，高的24位必然会补1，这样，其二进制补码其实已经不一致了，&0xff可以将高的24位置为0，低8位保持原样，这样做的目的就是为了保证二进制数据的一致性。
            bytes[i] = (byte) (n & 0xff);
        }
        String name = "";
        try {
            name = new String(bytes,code);
        } catch (UnsupportedEncodingException e) {
            // 转换异常
            e.printStackTrace();
        }
        return name.replaceAll("[\\u0000-\\u001f\b]","");
    }

    public static JSONObject analysisGBK(String str, JSONObject map) throws Exception {

        int p = 1;
        String typeface = "typeface" + p;
//        JSONObject map = new JSONObject();
        JSONObject objOne = new JSONObject();
        JSONObject objTwo = null;

        String threeStr = "";
        String content = "";
        String[] strArray = str.split("5C"); // 以 "%5C" 进行分割
        for (int i = 0; i < strArray.length; i++) {
            String string = strArray[i];
            String subStr = string.substring(0, 3);
            if (subStr.equals("02")) { // 说明这是一帧的开头
                continue;
            } else if (subStr.contains("53")) { //S %5C%53%30%30%
                threeStr = URLDecoder.decode(string.substring(3, 9), "GBK");
                insertMap("fontSpacing", threeStr, typeface, map, objOne, objTwo);
                if (string.length() == 9) {
                    continue;
                } else {
                    content = getValues(9, string);
                    insertMap("fontContent", content, typeface, map, objOne, objTwo);
                    if (content != "") {
                        objTwo = new JSONObject();
                        p = p + 1;
                        typeface = "typeface" + p;
                    }
                    continue;
                }
            } else if (subStr.contains("63")) { //c RRRGGGBBBYYY
                threeStr = URLDecoder.decode(string.substring(3, 39), "GBK");
                insertMap("fontColour", "红色", typeface, map, objOne, objTwo);
                if (string.length() == 39) {
                    continue;
                } else {
                    content = getValues(39, string);
                    insertMap("fontContent", content, typeface, map, objOne, objTwo);
                    if (content != "") {
                        objTwo = new JSONObject();
                        p = p + 1;
                        typeface = "typeface" + p;
                    }
                    continue;
                }
            } else if (subStr.contains("43")) { // C %30%30%30%30%30%30
                threeStr = URLDecoder.decode(string.substring(3, 12), "GBK");
                insertMap("fontX", threeStr, typeface, map, objOne, objTwo);
                threeStr = URLDecoder.decode(string.substring(12, 21), "GBK");
                insertMap("fontY", threeStr, typeface, map, objOne, objTwo);
                if (string.length() == 21) {
                    continue;
                } else {
                    content = getValues(21, string);
                    insertMap("fontContent", content, typeface, map, objOne, objTwo);
                    if (content != "") {
                        objTwo = new JSONObject();
                        p = p + 1;
                        typeface = "typeface" + p;
                    }
                    continue;
                }

            } else if (subStr.contains("66")) {
                String str2 = string.substring(3, 6);
                if (str2.equals("6B")) { // 代表楷体
                    insertMap("font", "楷体", typeface, map, objOne, objTwo);
                    threeStr = URLDecoder.decode(string.substring(6, 12), "GBK");
                    insertMap("fontHH", threeStr, typeface, map, objOne, objTwo);
                    threeStr = URLDecoder.decode(string.substring(12, 18), "GBK");
                    insertMap("fontWW", threeStr, typeface, map, objOne, objTwo);
                    if (string.length() == 18) {
                        continue;
                    } else {
                        content = getValues(18, string);
                        insertMap("fontContent", content, typeface, map, objOne, objTwo);
                        if (content != "") {
                            objTwo = new JSONObject();
                            p = p + 1;
                            typeface = "typeface" + p;
                        }
                        continue;
                    }
                } else if (str2.contains("68")) { // 代表黑体
                    insertMap("font", "黑体", typeface, map, objOne, objTwo);
                    threeStr = URLDecoder.decode(string.substring(6, 12), "GBK");
                    insertMap("fontHH", threeStr, typeface, map, objOne, objTwo);
                    threeStr = URLDecoder.decode(string.substring(12, 18), "GBK");
                    insertMap("fontWW", threeStr, typeface, map, objOne, objTwo);
                    if (string.length() == 18) {
                        continue;
                    } else {
                        content = getValues(18, string);
                        insertMap("fontContent", content, typeface, map, objOne, objTwo);
                        if (content != "") {
                            objTwo = new JSONObject();
                            p = p + 1;
                            typeface = "typeface" + p;
                        }
                        continue;
                    }
                }
            } else {
                continue;
            }
        }
        return map;
    }

    public static void insertMap(String key, String value, String typeface, JSONObject map, JSONObject objOne, JSONObject objTwo) throws JSONException {
        if (objTwo != null) {
            objTwo.put(key, value);
            map.put(typeface, objTwo);
        } else {
            objOne.put(key, value);
            map.put(typeface, objOne);
        }
    }

    public static String getValues(int i, String string) throws Exception {
        StringBuffer sb = new StringBuffer();
        Boolean mark = true;
        String threeStr = string.substring(i, string.length());
        for (int y = 0; y < threeStr.length(); y++) {
            if (threeStr.length() >= 6 * y + 6) {
                String str11 = threeStr.substring(6 * y, 6 * y + 3);
                String str22 = threeStr.substring(6 * y + 3, 6 * y + 6);
                if (str11.equals("%20")) {
                    if (str22.equals("%20")) {
                        String fourStr = URLDecoder.decode(threeStr.substring(6 * y, 6 * y + 6), "GBK");
                        sb.append(fourStr);
                    } else if (str22.equals("%00")) {
                        continue;
                    } else {
                        threeStr = string.substring(i + 3, string.length());
                        y = -1;
                    }
                } else if (str11.equals("%03") || str22.equals("%03")) {
                    break;
                } else {
                    // GBK (第一字节)0x81-0xFE（129-254） （第二字节）0x40-0xFE（64-254）
                    int firstByte = covert(str11.substring(1, 3));
                    int secondByte = covert(str22.substring(1, 3));
                    if (firstByte < 129 || firstByte > 254 || secondByte < 64 || secondByte > 254) {
                        continue;
                    } else {
                        String fourStr = URLDecoder.decode(threeStr.substring(6 * y, 6 * y + 6), "GBK");
                        sb.append(fourStr);
                    }
                }
            } else {
                mark = false;
                break;
            }
        }
        return sb.toString();
    }

    public static int covert(String content) {
        int number = 0;
        String[] HighLetter = {"A", "B", "C", "D", "E", "F"};
        Map<String, Integer> map = new HashMap<>();
        for (int i = 0; i <= 9; i++) {
            map.put(i + "", i);
        }
        for (int j = 10; j < HighLetter.length + 10; j++) {
            map.put(HighLetter[j - 10], j);
        }
        String[] str = new String[content.length()];
        for (int i = 0; i < str.length; i++) {
            str[i] = content.substring(i, i + 1);
        }
        for (int i = 0; i < str.length; i++) {
            number += map.get(str[i]) * Math.pow(16, str.length - 1 - i);
        }
        return number;
    }

}
